

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="CodeHope">
  <meta name="author" content="CodeHope">
  <meta name="keywords" content="希望">
  <title>从MVVM到Vue源码学习 - CodeHope</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      
        
          
          
          
        
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/themes/prism-tomorrow.min.css" />
      
      
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/plugins/line-numbers/prism-line-numbers.min.css" />
      
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"quancundexiwang.wang","root":"/","version":"1.8.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":true,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"onlypost":true},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz","app_key":"hMuhiD4FRqhns4giqLiEH9HG","server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.3.0"></head>


<body>
  <header style="height: 80vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>CodeHope</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                村头
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                我
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('http://qiniuyun.quancundexiwang.wang/vuebg.png') repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="从MVVM到Vue源码学习">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-07-28 22:27" pubdate>
        2020年7月28日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      40
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">从MVVM到Vue源码学习</h1>
            
            <div class="markdown-body">
              <h1 id="写一个MVVM框架"><a href="#写一个MVVM框架" class="headerlink" title="写一个MVVM框架"></a>写一个MVVM框架</h1><blockquote>
<p>View-model 视图层</p>
</blockquote>
<h2 id="MVVM框架的三要素"><a href="#MVVM框架的三要素" class="headerlink" title="MVVM框架的三要素"></a>MVVM框架的三要素</h2><ul>
<li><strong>1.数据响应式</strong> :监听数据在视图中更新<ul>
<li>Object.defineProperty(vue2.x)</li>
<li>Proxy(vue3.x)</li>
</ul>
</li>
<li><strong>2.模版引擎</strong><ul>
<li>插值</li>
<li>指令v-bind，v-on，v-model….</li>
</ul>
</li>
<li><strong>3.渲染</strong> 模版转化为真实dom<ul>
<li>模版=&gt;vdom=&gt;dom</li>
</ul>
</li>
</ul>
<p>涉及类型介绍</p>
<ul>
<li><strong>Observer</strong> 劫持数据执行数据响应化(判断类型将所有数据的类型都转为值类型)</li>
<li><strong>Compile</strong> 编译器，编译模版，初始化视图，收集依赖，更新函数 watcher创建</li>
<li><strong>Watcher</strong> 执行更新函数（更新dom） </li>
<li><strong>Dep</strong> 管理多个watcher 批量更新</li>
</ul>
<h2 id="1-Step1实现数据响应式✅"><a href="#1-Step1实现数据响应式✅" class="headerlink" title="1.Step1实现数据响应式✅"></a>1.Step1实现数据响应式✅</h2><blockquote>
<p>基于Vue2.x使用的<code>Object.defineProperty</code></p>
</blockquote>
<h3 id="1-1认识一下Object-defineProperty"><a href="#1-1认识一下Object-defineProperty" class="headerlink" title="1.1认识一下Object.defineProperty"></a>1.1认识一下<code>Object.defineProperty</code></h3><blockquote>
<p><code>Object.defineProperty()</code> 方法会直接在一个对象上定义一个新属性，或者修改一个对象的现有属性，并返回此对象。</p>
</blockquote>
<blockquote>
<p>参数</p>
</blockquote>
<ul>
<li><strong>obj</strong> 要定义属性的对象。</li>
<li><strong>prop</strong> 要定义或修改的属性的名称或 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> 。</li>
<li><strong>descriptor</strong> 要定义或修改的属性描述符。</li>
</ul>
<h3 id="1-2-模仿vue的形式，框架构造函数"><a href="#1-2-模仿vue的形式，框架构造函数" class="headerlink" title="1.2 模仿vue的形式，框架构造函数"></a>1.2 模仿vue的形式，框架构造函数</h3><div class="code-wrapper"><pre class="line-numbers language-html" data-language="html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript">
    <span class="token keyword">const</span> cue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Cue</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span>
        el<span class="token operator">:</span><span class="token string">"#app"</span><span class="token punctuation">,</span>
        data<span class="token operator">:</span><span class="token punctuation">&#123;</span>
            name<span class="token operator">:</span><span class="token number">1</span><span class="token punctuation">,</span>
            school_list<span class="token operator">:</span><span class="token punctuation">[</span>
                <span class="token punctuation">&#123;</span>school_name<span class="token operator">:</span><span class="token string">"演示1"</span><span class="token punctuation">,</span>id<span class="token operator">:</span><span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                <span class="token punctuation">&#123;</span>school_name<span class="token operator">:</span><span class="token string">"演示2"</span><span class="token punctuation">,</span>id<span class="token operator">:</span><span class="token number">2</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                <span class="token punctuation">&#123;</span>
                    school_name<span class="token operator">:</span><span class="token string">"演示3"</span><span class="token punctuation">,</span>id<span class="token operator">:</span><span class="token number">3</span><span class="token punctuation">,</span>
                    children<span class="token operator">:</span><span class="token punctuation">[</span>
                        <span class="token punctuation">&#123;</span>grade<span class="token operator">:</span><span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                        <span class="token punctuation">&#123;</span>grade<span class="token operator">:</span><span class="token number">2</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                        <span class="token punctuation">&#123;</span>grade<span class="token operator">:</span><span class="token number">3</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                    <span class="token punctuation">]</span>
                <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">]</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
   console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>cue<span class="token punctuation">.</span>$data<span class="token punctuation">.</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//目的：被拦截的对象的访问和修改都会被拦截到</span>
   cue<span class="token punctuation">.</span>$data<span class="token punctuation">.</span>school_list<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">.</span>children<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>grade <span class="token operator">=</span> <span class="token number">222</span><span class="token punctuation">;</span>
</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<h3 id="1-3-Observer对属性进行拦截响应化"><a href="#1-3-Observer对属性进行拦截响应化" class="headerlink" title="1.3 Observer对属性进行拦截响应化"></a>1.3 Observer对属性进行拦截响应化</h3><div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">class</span> <span class="token class-name">Cue</span> <span class="token punctuation">&#123;</span>
    $el
    $data
   
    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter">$options</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>$el <span class="token operator">=</span> $options<span class="token punctuation">.</span>el<span class="token punctuation">;</span> <span class="token comment">//获取操作的dom 节点</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>$data <span class="token operator">=</span> $options<span class="token punctuation">.</span>data<span class="token punctuation">;</span> <span class="token comment">//获取拦截的对象属性</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">Observe</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>$data<span class="token punctuation">)</span> <span class="token comment">// 放入观察者</span>
    <span class="token punctuation">&#125;</span>

    <span class="token function">Observe</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">const</span> keys <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">keys</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//对对象进行遍历递归，保证拦截的值都是属性值</span>
        keys<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">key<span class="token punctuation">,</span>index</span><span class="token punctuation">)</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">typeof</span> data<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token operator">==</span><span class="token string">"object"</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">Observe</span><span class="token punctuation">(</span>data<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">)</span>
            <span class="token punctuation">&#125;</span><span class="token keyword">else</span><span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">DefineReactive</span><span class="token punctuation">(</span>data<span class="token punctuation">,</span>key<span class="token punctuation">,</span>data<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token comment">//属性值的放入拦截，进行值的监听</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">DefineReactive</span><span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span>key<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
       Object<span class="token punctuation">.</span><span class="token function">defineProperty</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span>key<span class="token punctuation">,</span><span class="token punctuation">&#123;</span>
           <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//被访问的时候返回值</span>
               <span class="token keyword">return</span> value
           <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
           <span class="token function">set</span><span class="token punctuation">(</span>newValue<span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//被重新复制的时候 我们可以在这里做一些其他操作比如说视图的更新，日志打印。。。</span>
               <span class="token keyword">if</span><span class="token punctuation">(</span> newValue <span class="token operator">!==</span>value<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span>value<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token string">=></span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span>newValue<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//1=>222</span>
                value<span class="token operator">=</span> newValue
                 <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> newValue
               <span class="token punctuation">&#125;</span><span class="token keyword">else</span><span class="token punctuation">&#123;</span>
                   <span class="token keyword">return</span> value
               <span class="token punctuation">&#125;</span>
           <span class="token punctuation">&#125;</span>
       <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
  <span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token comment">//页面更新。</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<blockquote>
<p>测试</p>
</blockquote>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token function">setInterval</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
    cue<span class="token punctuation">.</span>$data<span class="token punctuation">.</span>num <span class="token operator">+=</span><span class="token number">1</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">,</span><span class="token number">2000</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></div>
<p><img src="https://raw.githubusercontent.com/changhao970630/cdn/master/images/20200729160644.png" srcset="/img/loading.gif" alt="测试结果"><br>成功监听到数据到变化</p>
<h3 id="1-4-小问题❓"><a href="#1-4-小问题❓" class="headerlink" title="1.4 小问题❓"></a>1.4 小问题❓</h3><ul>
<li>1.如果只是按照上面的代码如果我这样子给对象中的某个值 赋予一个对象呢？ ✅</li>
</ul>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js">cue<span class="token punctuation">.</span>$data<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token punctuation">&#123;</span>
       a<span class="token operator">:</span><span class="token number">1</span>
<span class="token punctuation">&#125;</span>
   cue<span class="token punctuation">.</span>$data<span class="token punctuation">.</span>name<span class="token punctuation">.</span>a <span class="token operator">=</span> <span class="token number">2</span> <span class="token punctuation">;</span><span class="token comment">//这里不能触发响应式set的监听，不过值是可以赋值成功的</span>
   console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>cue<span class="token punctuation">.</span>$data<span class="token punctuation">.</span>name<span class="token punctuation">.</span>a<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>解决方法</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token function">DefineReactive</span><span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span>key<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
       <span class="token keyword">const</span> _this <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
       Object<span class="token punctuation">.</span><span class="token function">defineProperty</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span>key<span class="token punctuation">,</span><span class="token punctuation">&#123;</span>
           <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//被访问的时候返回值</span>
               <span class="token keyword">return</span> value
           <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
           <span class="token function">set</span><span class="token punctuation">(</span>newValue<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            _this<span class="token punctuation">.</span><span class="token function">Observe</span><span class="token punctuation">(</span>newValue<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//对新的newValue进行一次观察是值还是对象，防止对象中的引用类型容易出现错误！</span>
               <span class="token keyword">if</span><span class="token punctuation">(</span> newValue <span class="token operator">!==</span> value<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span>value<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token string">=></span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span>newValue<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                value<span class="token operator">=</span> newValue
                <span class="token keyword">return</span> newValue
               <span class="token punctuation">&#125;</span><span class="token keyword">else</span><span class="token punctuation">&#123;</span>
                   <span class="token keyword">return</span> value
               <span class="token punctuation">&#125;</span>
           <span class="token punctuation">&#125;</span>
       <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<ul>
<li><p>2.我们想和vue一样通过(xxx点name) 这样直接访问到实例中的data数据而不要在写一次data<br>我们可以通过代理data数据，劫持然后改变他的get&amp;set</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript">  <span class="token function">proxy</span><span class="token punctuation">(</span><span class="token parameter">vm<span class="token punctuation">,</span><span class="token constant">VM_KEY</span></span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//实例对象vm 和 实例中的属性 VM_KEY（$data,$el...）</span>
    Object<span class="token punctuation">.</span><span class="token function">keys</span><span class="token punctuation">(</span>vm<span class="token punctuation">[</span><span class="token constant">VM_KEY</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token parameter">key</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
        Object<span class="token punctuation">.</span><span class="token function">defineProperty</span><span class="token punctuation">(</span>vm<span class="token punctuation">,</span>key<span class="token punctuation">,</span><span class="token punctuation">&#123;</span><span class="token comment">//vm 和 data中的key</span>
            <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> vm<span class="token punctuation">[</span><span class="token constant">VM_KEY</span><span class="token punctuation">]</span><span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token comment">//返回vm中data中key的值</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token function">set</span><span class="token punctuation">(</span>newValue<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                vm<span class="token punctuation">[</span><span class="token constant">VM_KEY</span><span class="token punctuation">]</span><span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">=</span> newValue<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
  <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>这个在new 实例化就要对实例的data属性进行代理</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"> <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter">$options</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token operator">...</span><span class="token operator">...</span><span class="token punctuation">.</span>etc
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">proxy</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span><span class="token string">'$data'</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
  
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>cue<span class="token punctuation">.</span>num<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//1->这样我们就可以直接这样访问啦！</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<h3 id="1-5-遗留问题❓-待补充🚧"><a href="#1-5-遗留问题❓-待补充🚧" class="headerlink" title="1.5 遗留问题❓(待补充🚧)"></a>1.5 遗留问题❓(待补充🚧)</h3></li>
</ul>
<p>对象中使用数组的时候，也不能出发set,需要替换数组的实例的原型方法！让他改变数组的时候，做一些监听操作。</p>
<h3 id="1-6-用到的闭包小知识点"><a href="#1-6-用到的闭包小知识点" class="headerlink" title="1.6 用到的闭包小知识点"></a>1.6 用到的闭包小知识点</h3><div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token function">DefineReactive</span><span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span>key<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//1⃣️这里的value ，通过函数里面的get方法 返回当前函数的作用域外部，</span>
       Object<span class="token punctuation">.</span><span class="token function">defineProperty</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span>key<span class="token punctuation">,</span><span class="token punctuation">&#123;</span>
           <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//被访问的时候返回值</span>
               <span class="token keyword">return</span> value
           <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
         <span class="token operator">...</span><span class="token operator">...</span><span class="token punctuation">.</span>
       <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>

xxx<span class="token punctuation">.</span>value <span class="token comment">//2⃣️在全局可以持续访问，不会被释放就形成了闭包。</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<h2 id="2-Step2-Compile编译器✅"><a href="#2-Step2-Compile编译器✅" class="headerlink" title="2.Step2 Compile编译器✅"></a>2.Step2 Compile编译器✅</h2><blockquote>
<p>解析模版中的节点</p>
</blockquote>
<ul>
<li>递归遍历dom树。<ul>
<li>如果是文本，判断是否为插值表达式</li>
<li>如果是元素遍历他的属性，看是否有指令或者事件。</li>
</ul>
</li>
</ul>
<p>知识点:</p>
<blockquote>
<p>1.element   元素节点的属性值为 1</p>
<p>2.text      文本节点的属性值为3</p>
<p>3.空格也算文本节点</p>
<p>4.RegExp.$1是RegExp的一个属性,指的是bai与正则表达式匹配du的第一个 子匹配(以括号为标志)字符串，以此类推，RegExp.$2，RegExp.$3，..RegExp.$99总共可以有99个匹配</p>
</blockquote>
<ul>
<li><p>1.首先创建一个模仿vue的标准htmlDOM结构</p>
<div class="code-wrapper"><pre class="line-numbers language-html" data-language="html"><code class="language-html">//初期防止空格影响后面处理空格
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>app<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">></span></span>&#123;&#123;num&#125;&#125;<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span> <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre></div></li>
<li><p>2.创建一个编译器的类Compile,获取dom和实例</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token keyword">class</span> <span class="token class-name">Compile</span><span class="token punctuation">&#123;</span>
    $vm<span class="token punctuation">;</span> <span class="token comment">//vm实例</span>
    $el<span class="token punctuation">;</span> <span class="token comment">//dom节点</span>
    <span class="token comment">//匹配&#123;&#123;&#125;&#125; ,(.*)可以将括号中内容分组通过$1~$99拿到</span>
    insertReg <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RegExp</span><span class="token punctuation">(</span><span class="token regex"><span class="token regex-delimiter">/</span><span class="token regex-source language-regex">\&#123;\&#123;(.*)\&#125;\&#125;</span><span class="token regex-delimiter">/</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter">el<span class="token punctuation">,</span>vm</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>$el <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>$vm <span class="token operator">=</span> vm<span class="token punctuation">;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>$el<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token comment">//compile方法递归拿出所有层级的dom节点</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">compile</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>$el<span class="token punctuation">)</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript">   <span class="token comment">//1⃣️遍历el的中的dom树</span>
<span class="token function">compile</span><span class="token punctuation">(</span><span class="token parameter">el</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token comment">//childNodes是个伪数组，需要Array.from转化。</span>
    <span class="token keyword">const</span> childNodes <span class="token operator">=</span> el<span class="token punctuation">.</span>childNodes<span class="token punctuation">;</span>
    Array<span class="token punctuation">.</span><span class="token function">from</span><span class="token punctuation">(</span>childNodes<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token parameter">node</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
        <span class="token comment">//判断子节点是否有子节点</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>node<span class="token punctuation">.</span>childNodes<span class="token operator">&amp;&amp;</span>node<span class="token punctuation">.</span>childNodes<span class="token punctuation">.</span>length<span class="token operator">></span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">compile</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span>
      <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isElement</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"是个元素节点,调用编译元素节点的方法"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">compileElement</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span>
        <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isText</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"是个文本节点，调用编译文本节点的方法"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">compileText</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div></li>
<li><p>3.创建编译文本节点和元素节点的函数</p>
<ol>
<li><p>编译文本节点，将实例中data的key与插值表达式所匹配的一一对应赋值.</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">compileText</span><span class="token punctuation">(</span><span class="token parameter">node</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token comment">//因为匹配到到对象到key在vm实例中，所以可以直接这样取到num</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>RegExp<span class="token punctuation">.</span>$<span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//num</span>
    <span class="token comment">//这里我们把当前的节点的值就放入了对应的数据</span>
    node<span class="token punctuation">.</span>textContent <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>$vm<span class="token punctuation">[</span>RegExp<span class="token punctuation">.</span>$<span class="token number">1</span><span class="token punctuation">]</span>
     <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>我们看一下效果<br><img src="https://raw.githubusercontent.com/changhao970630/cdn/master/images/20200729183211.png" srcset="/img/loading.gif" alt="插值表达式实现"><br>这样就实现了插值表达式嵌入vue实例里面的值</p>
</li>
<li><p>我们接下来需要编译我们的元素节点</p>
<blockquote>
<p>比如元素节点我们使用v-text向dom的元素节点中插入我们vue实例的值。</p>
</blockquote>
<blockquote>
<p>这一次我们把dom结构变成下面这样。</p>
</blockquote>
<div class="code-wrapper"><pre class="line-numbers language-html" data-language="html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>app<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">></span></span>&#123;&#123;num&#125;&#125;<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span> <span class="token attr-name">c-text</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>num<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></div>
<p>首先我们定义我们的 编译元素节点的函数</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"> <span class="token function">compileElement</span><span class="token punctuation">(</span><span class="token parameter">node</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>node<span class="token punctuation">.</span>attributes<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//这个节点所有的属性</span>
    Array<span class="token punctuation">.</span><span class="token function">from</span><span class="token punctuation">(</span>node<span class="token punctuation">.</span>attributes<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token parameter">attr</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
        <span class="token comment">//attr属性是name-value的对象类型</span>
        <span class="token keyword">const</span> attrName <span class="token operator">=</span> attr<span class="token punctuation">.</span>name<span class="token punctuation">;</span><span class="token comment">//v-text</span>
        <span class="token keyword">const</span> value <span class="token operator">=</span> attr<span class="token punctuation">.</span>value<span class="token punctuation">;</span><span class="token comment">//num</span>
        <span class="token comment">//我们在这里需要先判断是不是我们要的属性->是不是指令 c-开头</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isCDirective</span><span class="token punctuation">(</span>attrName<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 在这里也要判断一下指令的类型 text,html....etc</span>
            <span class="token comment">// 所有我们先把c-xxx 的xxx截取出来</span>
            <span class="token keyword">const</span> ctype <span class="token operator">=</span> attrName<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ctype<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//text 这里就是我们当前案例使用的v-text的text类型</span>
            <span class="token keyword">switch</span> <span class="token punctuation">(</span>ctype<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">case</span> <span class="token string">"text"</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">textDirective</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token operator">...</span><span class="token punctuation">.</span>这里后面还有其他指令的判断
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
  
<span class="token function">isCDirective</span><span class="token punctuation">(</span><span class="token parameter">attrName</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">//判断属性值是不是c-开头的指令</span>
    <span class="token keyword">return</span> attrName<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span><span class="token string">"c-"</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token function">textDirective</span><span class="token punctuation">(</span><span class="token parameter">node<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">//v-text指令对应的操作</span>
    <span class="token comment">//node节点中的内容注入当前实例data中value对应的数据</span>
    node<span class="token punctuation">.</span>textContent <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>$vm<span class="token punctuation">[</span>value<span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="https://github.com/changhao970630/cdn/blob/master/images/20200729185938.png?raw=true" srcset="/img/loading.gif" alt="自定义指令注入数据成功"></p>
</li>
</ol>
</li>
</ul>
<p>我们在添加自定义的c-html指令尝试一下</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js">data<span class="token operator">:</span><span class="token punctuation">&#123;</span>
    num<span class="token operator">:</span><span class="token number">1</span><span class="token punctuation">,</span>
    htmlmsg<span class="token operator">:</span><span class="token string">"&lt;p style='color:red;font-size:2rem;'>c-html自定义指令渲染&lt;/p>"</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>添加指令对应的处理方法</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token operator">...</span><span class="token operator">...</span>

<span class="token keyword">case</span> <span class="token string">"html"</span><span class="token operator">:</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">htmlDirective</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span>value<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">htmlDirective</span><span class="token punctuation">(</span><span class="token parameter">node<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    node<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>$vm<span class="token punctuation">[</span>value<span class="token punctuation">]</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></div>
<div class="code-wrapper"><pre class="line-numbers language-html5" data-language="html5"><code class="language-html5">&lt;div id&#x3D;&quot;app&quot;&gt;&lt;p&gt;&#123;&#123;num&#125;&#125;&lt;&#x2F;p&gt;&lt;p c-text&#x3D;&quot;num&quot;&gt;&lt;&#x2F;p&gt;&lt;p c-html&#x3D;&quot;htmlmsg&quot;&gt;&lt;&#x2F;p&gt;&lt;&#x2F;div&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></div>
<p><img src="https://raw.githubusercontent.com/changhao970630/cdn/master/images/20200729190338.png" srcset="/img/loading.gif" alt="c-html注入成功"><br>这样c-html也成功啦</p>
<blockquote>
<p>我们到这个阶段完成了数据到初始化渲染，但是如果我的数据变化到时候并没有在set的时候更新页面<br>所以我们下一步就要做的是视图的更新</p>
</blockquote>
<p>首先因为不管是数据的初始化还是数据的更新，都是一个节点对应一个数据，我们上面更新是每一种情况写一个函数，如果我们加入更新的话，因为更新节点的操作比较统一，我们不需要每一个都写一遍，所以我们改一下初始化的函数</p>
<p>Before</p>
<p><img src="https://raw.githubusercontent.com/changhao970630/cdn/master/images/20200730103905.png" srcset="/img/loading.gif"></p>
<p>After</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">update</span><span class="token punctuation">(</span><span class="token parameter">node<span class="token punctuation">,</span>name<span class="token punctuation">,</span>key</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>  <span class="token comment">//节点 类型 data中的key</span>
     <span class="token comment">//初始化操作</span>
     <span class="token keyword">const</span> fn <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">[</span>name<span class="token operator">+</span><span class="token string">"Update"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
     fn<span class="token operator">&amp;&amp;</span><span class="token function">fn</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span><span class="token keyword">this</span><span class="token punctuation">.</span>$vm<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">)</span>
	<span class="token comment">//更新操作       </span>
 <span class="token punctuation">&#125;</span>
	 <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>​    调用的时候把当前节点 ,注入的类型（html,text…）还有对应注入的data里面的key传过来</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span>ctype<span class="token punctuation">,</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token comment">//生成ctypeUpdate函数进行相应的操作</span>
  <span class="token function">htmlUpdate</span><span class="token punctuation">(</span><span class="token parameter">node<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        node<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> value
    <span class="token punctuation">&#125;</span>
  <span class="token function">textUpdate</span><span class="token punctuation">(</span><span class="token parameter">node<span class="token punctuation">,</span>value</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>node<span class="token punctuation">.</span>nodeType<span class="token punctuation">)</span><span class="token punctuation">;</span>
        node<span class="token punctuation">.</span>textContent <span class="token operator">=</span> value
  <span class="token punctuation">&#125;</span>
<span class="token comment">//初始化渲染dom都执行对应的方法，这些方法是从一个update中分发出来的</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<h2 id="3-Step3-Watcher-实例分析✅"><a href="#3-Step3-Watcher-实例分析✅" class="headerlink" title="3.Step3 Watcher 实例分析✅"></a>3.Step3 <strong>Watcher</strong> 实例分析✅</h2><p>​        下面我们考虑数据更新时的操作，</p>
<p>​        我们定义一个watcher 来执行更新的操作，肯定要知道更新的拿一个节点，更新了哪个数据，每一个节点的更新都保存在一个,watcher实例中！然后放入收集依赖的地方在set的地方统一更新</p>
<div class="code-wrapper"><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token keyword">class</span> <span class="token class-name">Watcher</span> <span class="token punctuation">&#123;</span>
    vm<span class="token punctuation">;</span> <span class="token comment">//拿到实例</span>
    key<span class="token punctuation">;</span> <span class="token comment">//拿到数据key值</span>
    updateFn<span class="token punctuation">;</span><span class="token comment">//传入的更新方法</span>
    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter">vm<span class="token punctuation">,</span>key<span class="token punctuation">,</span>updateFn</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>vm <span class="token operator">=</span> vm<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>key <span class="token operator">=</span> key<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>updateFn <span class="token operator">=</span> updateFn<span class="token punctuation">;</span>
       <span class="token comment">//这里的操作是 把当前watcher实例保存起来，你可以存入任何地方，🌟</span>
       <span class="token comment">//只要可以访问的到，然后把当前watcher对应实例取出来就行。</span>
        Dependence<span class="token punctuation">.</span>target <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>vm<span class="token punctuation">[</span><span class="token keyword">this</span><span class="token punctuation">.</span>key<span class="token punctuation">]</span><span class="token comment">//触发getter，可以生成容器</span>
        Dependence<span class="token punctuation">.</span>target <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span> <span class="token comment">//使用结束立马清空</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
      	<span class="token comment">//call改变this的指向，指向vm实例的数据，</span>
      	<span class="token comment">//这里的updateFn是我们从外面传入的更新数据</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">updateFn</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>vm<span class="token punctuation">,</span><span class="token keyword">this</span><span class="token punctuation">.</span>vm<span class="token punctuation">[</span><span class="token keyword">this</span><span class="token punctuation">.</span>key<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>​    <img src="https://cdn.jsdelivr.net/gh/changhao970630/cdn@master/images/20200730114546.png" srcset="/img/loading.gif"></p>
<p>​    到此呢我们的watcher就收集到了需要更新的节点，需要更新到节点的值，已经对应节点的更新函数。</p>
<p>​    下一步我们就要将每一个更新的操作交给一个容器，然后容器去在拦截到数据变化set的时候去遍历所有的更新方法，去调用每一个watcher的更新方法（update）</p>
<h2 id="4-Step4-Dep-管理watcher更新✅"><a href="#4-Step4-Dep-管理watcher更新✅" class="headerlink" title="4.Step4 Dep 管理watcher更新✅"></a>4.Step4 Dep 管理watcher更新✅</h2><div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">class</span> <span class="token class-name">Dependence</span><span class="token punctuation">&#123;</span> <span class="token comment">//管理相关Watcher实例</span>
    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>deps <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span><span class="token comment">// 初始化容器</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">addDep</span><span class="token punctuation">(</span><span class="token parameter">dep</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token comment">//dep指的就是watcher实例</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>deps<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>dep<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//放入watcher实例</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token comment">//通知更新</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>deps<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token parameter">dep</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
            dep<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">//调用每一个watcher的更新方法</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p>​    然后我们在监听每一个数据的地方</p>
<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token function">DefineReactive</span><span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span> key<span class="token punctuation">,</span> value</span> <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">const</span> _this <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
        <span class="token keyword">const</span> dep <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Dependence</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
        Object<span class="token punctuation">.</span><span class="token function">defineProperty</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span> key<span class="token punctuation">,</span> <span class="token punctuation">&#123;</span>
            <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">//被访问的时候返回值</span>
              <span class="token comment">//因为每一个值都要走拦截，对应当前属性值自己的节点和属性</span>
              <span class="token comment">//Dependence.target取出的watcher实例也是对应当前值</span>
                Dependence<span class="token punctuation">.</span>target <span class="token operator">&amp;&amp;</span> dep<span class="token punctuation">.</span><span class="token function">addDep</span><span class="token punctuation">(</span>Dependence<span class="token punctuation">.</span>target<span class="token punctuation">)</span>
                <span class="token keyword">return</span> value
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token function">set</span><span class="token punctuation">(</span>newValue<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> 
                _this<span class="token punctuation">.</span><span class="token function">Observe</span><span class="token punctuation">(</span>newValue<span class="token punctuation">)</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>newValue <span class="token operator">!==</span> value<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token comment">// _this.Observe(newValue)</span>
                    dep<span class="token punctuation">.</span><span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    value <span class="token operator">=</span> newValue
                    <span class="token keyword">return</span> newValue
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> value
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<p><img src="https://cdn.jsdelivr.net/gh/changhao970630/cdn@master/images/20200730122756.gif" srcset="/img/loading.gif" alt="Jul-30-2020 12-27-22"></p>
<p>成功！到目前我们完成了 属性 监听 拦截 收集 更新的操作，但是并没有加入diff算法，如果很多个属性节点，就会有多个实例，性能就很差，后面我们会根据diff算法在进行学习。</p>
<p>Observer是拦截监听传入的所有数据的变化。<br>Watcher是收集每一个dom节点，对应的数据变化，带有更新当前收集到的节点数据更新的函数<br>Dependences 是存储一个个Watcher的实例对象，在每一次get,set的时候去执行所有watcher的更新方法，进行视图的更新。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/vue%E6%A1%86%E6%9E%B6/">vue框架</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E4%BB%8EMVVM%E5%88%B0Vue%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0/">从MVVM到Vue源码学习</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/posts/6860/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">剖析VUE源码</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/posts/45054/">
                        <span class="hidden-mobile">Vue实现自己的小组件</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    Fluid.utils.waitElementVisible('vcomments', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz",
          app_key: "hMuhiD4FRqhns4giqLiEH9HG",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the
    <a target="_blank" href="https://valine.js.org" rel="nofollow noopener noopener">comments powered by Valine.</a>
  </noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    

  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        豫ICP备20009912号-1
      </a>
    </span>
    
  </div>


  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":true,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    
      <script  src="/js/lazyload.js" ></script>
    
  



  
    
  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "http://qiniuyun.quancundexiwang.wang/xmlSearch.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
